{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "%matplotlib inline\n",
    "\n",
    "import numpy as np\n",
    "import matplotlib.pyplot as plt"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def func(x):\n",
    "    return np.sin(np.pi * x) * (1 - x)\n",
    "\n",
    "xs = np.linspace(-1, 1, 100)\n",
    "ys = func(xs)\n",
    "plt.plot(xs, ys)\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "sample_x = np.linspace(-1, 1, 10)\n",
    "sample_y = func(sample_x)\n",
    "plt.scatter(sample_x, sample_y)\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def kernel_func(x_ref, x_input, sigma=1):\n",
    "    return np.exp(-(x_input-x_ref)**2 / (2 * sigma**2))\n",
    "\n",
    "xs = np.linspace(-1, 1, 100)\n",
    "ys = kernel_func(0, xs)\n",
    "plt.plot(xs, ys)\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def kernel_regression(xs, ys, x_input, sigma=1):\n",
    "    # xs: [n, ]\n",
    "    # ys: [n, ]\n",
    "    # x_input: [m, ]\n",
    "    N = xs.shape[0]\n",
    "    xs = np.expand_dims(xs, 1)\n",
    "    ys = np.expand_dims(ys, 1)\n",
    "    x_input = np.expand_dims(x_input, 0)\n",
    "    x_input = np.repeat(x_input, N, 0)\n",
    "    weight = kernel_func(xs, x_input, sigma) # [n, m]\n",
    "    weight_sum = np.sum(weight, 0)\n",
    "    weight_dot = weight.T @ ys\n",
    "    weight_dot = np.squeeze(weight_dot, 1)\n",
    "    res = weight_dot / weight_sum\n",
    "    return res\n",
    "\n",
    "sigma = 0.5\n",
    "xs = np.linspace(-1, 1, 100)\n",
    "ys = kernel_regression(sample_x, sample_y, xs, sigma)\n",
    "plt.title(f'sigma = {sigma}')\n",
    "plt.plot(xs, ys)\n",
    "plt.show()\n"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "pt",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.13"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
